import { topCategory } from '@/api/constants'
import { findAllCategory } from '@/api/category'
import {
  GET_CATEGORY,
  SHOW_CATEGORY,
  HIDE_CATEGORY
} from './actionTypes'
// 分类模块
export default {
  namespaced: true,

  state() {
    return {
      // 分类信息集合(给一个默认的)
      categoryList: topCategory.map(item => ({ name: item }))
    }
  },
  mutations: {
    [GET_CATEGORY](state, list) {
      state.categoryList = list
    },
    // 修改当前一级分类下的open数据为true
    [SHOW_CATEGORY](state, item) {
      const category = state.categoryList.find(category => category.id === item.id)
      category.open = true
    },
    // 修改当前一级分类下的open数据为false
    [HIDE_CATEGORY](state, item) {
      const category = state.categoryList.find(category => category.id === item.id)
      category.open = false
    }
  },
  actions: {
    // 获取分类
    async [GET_CATEGORY]({ commit }) {
      const { result } = await findAllCategory()
      // 给一级分类加上一个控制二级分类显示隐藏的数据
      result.forEach(item => {
        item.open = false
      })
      console.log('result', result)
      commit(GET_CATEGORY, result)
    },
    [SHOW_CATEGORY]({ commit }, item) {
      commit(SHOW_CATEGORY, item)
    },
    [HIDE_CATEGORY]({ commit }, item) {
      commit(HIDE_CATEGORY, item)
    },
  }
}
